<template>
  <div class="stage app-container">
    <a-button type="primary" @click="showAddModal">
      <template #icon>
        <icon-plus />
      </template>
      新建
    </a-button>
    <a-table :columns="columns" :data="stageData" :pagination="false" :scroll="{ y: 'calc(100vh - 250px)' }">
      <template #status="{ record }">
        <a-switch v-model="record.status" @change="changeStatus(record)" :unchecked-value="0" :checked-value="1" />
      </template>
      <template #operate="{ record }">
        <a-button type="text" size="mini" @click="showEditModal(record)">编辑</a-button>
        <a-button type="text" size="mini" @click="handelDelStage(record)">删除</a-button>
      </template>
    </a-table>
  </div>
  <a-modal :visible="visbible" hide-title simple width="470" @ok="handleAddOk" @cancel="handleCloseAddAndEdit">
    <div class="model-content">
      <CustomTitle title="业务阶段" />
      <a-form :model="form" auto-label-width ref="formRef">
        <a-form-item label="客户阶段" field="stageName" :rules="[{ maxLength: 10, message: '长度不能超过10个字符' }, ...rules]">
          <a-input placeholder="请输入" v-model="form.stageName" />
        </a-form-item>
        <a-form-item label="排序" field="showSeq" :rules="[...rules]">
          <a-input-number
            v-model="form.showSeq"
            placeholder="数值越小越靠前(只能填正整数)"
            :formatter="(value:number) => `${value}`"
            :precision="0"
            :parser="(value:number) => value.replace('.', '')"
            :min="0"
            :max="10000000"
          />
        </a-form-item>
        <a-form-item label="类型" field="stageType" :rules="[...rules]">
          <a-radio-group :disabled="form.stageSettingId?true:false" v-model="form.stageType" :options="businessTypeOptions" />
        </a-form-item>
        <a-form-item label="是否启用" field="status" :rules="[...rules]">
          <a-switch v-model="form.status" :checked-value="1" :unchecked-value="0" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
  <a-modal
    :visible="isAlertModal"
    @ok="handleDelStageOk"
    @cancel="handelDelStageClose"
    okText="确定"
    cancelText="取消"
    width="400px"
    unmountOnClose
    :closable="false"
  >
    <div class="modal-message">
      <div class="del-name">{{ delDetail.stageName }}</div>
      <div class="del-tip">您确定要删除该阶段吗？</div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue";
import { Message } from "@arco-design/web-vue";
import { cloneDeep } from "lodash";
import CustomTitle from "@/components/CustomTitle/index.vue";
import { getStageList as stageList, updateStage, delStage } from "@/apis/system";
import { dictByType } from "@/apis";
import type { DictData } from "@/apis";
import type { CustomerStage } from "@/apis/system/type";

defineProps(["rules"]);
const { proxy }: any = getCurrentInstance();

const columns = [
  {
    title: "序号",
    dataIndex: "ordinal"
  },
  {
    title: "阶段名称",
    dataIndex: "stageName"
  },
  {
    title: "禁用/启用",
    slotName: "status"
  },
  {
    title: "操作",
    slotName: "operate"
  }
];

const visbible = ref(false);
const stageData = ref<CustomerStage[]>([]);
const initForm = {
  stageName: "",
  status: 1,
  showSeq: 1,
  stageType: ""
};
const form = ref<CustomerStage>({ ...initForm });
/**
 * 类型
 */
type BusinessType = {
  label: string;
  value: number;
};
const businessTypeOptions = ref<BusinessType[]>([]);
const getBusinessType = async () => {
  const { data } = await dictByType("crm_stage_type");
  businessTypeOptions.value =
    data?.map((v: DictData) => {
      if (!form.value.stageType) {
        v.dictLabel === "客户营销" && (form.value.stageType = Number(v.dictValue));
      }
      return { label: v.dictLabel, value: Number(v.dictValue) };
    }) || [];
};

const showAddModal = () => {
  getBusinessType();
  visbible.value = true;
};

const showEditModal = (item: CustomerStage) => {
  if (!item || !item.stageSettingId) {
    return Message.error("请选择要编辑的阶段");
  }
  getBusinessType();
  form.value = { ...item };
  visbible.value = true;

};
const handleCloseAddAndEdit = async () => {
  await nextTick();
  proxy.$refs.formRef.resetFields();
  form.value = { ...initForm };
  visbible.value = false;
};

const verify = (): Promise<boolean> => {
  return new Promise(async resolve => {
    proxy.$refs.formRef.validate((error: any) => {
      resolve(error == void 0);
    });
  });
};
const handleAddOk = async () => {
  if (!(await verify())) return;
  await updateStage(form.value);
  getStageList();
  handleCloseAddAndEdit();
  Message.success("操作成功");
};

const isAlertModal = ref(false);
const delDetail = ref<CustomerStage>({ ...initForm });
const handelDelStage = (item: CustomerStage) => {
  delDetail.value = cloneDeep(item);
  isAlertModal.value = true;
};
const handleDelStageOk = async () => {
  await delStage(delDetail.value.stageSettingId as string);
  Message.success("删除成功");
  getStageList();
  handelDelStageClose();
};
const handelDelStageClose = () => {
  delDetail.value = { ...initForm };
  isAlertModal.value = false;
};

const changeStatus = async (item: CustomerStage) => {
  form.value = { ...item };
  await updateStage(form.value);
  form.value = { ...initForm };
  getStageList();
  Message.success("操作成功");
};

const getStageList = async () => {
  const { data } = await stageList();
  const list = data ?? [];
  stageData.value = list.map((v, i) => ({ ...v, ordinal: i + 1 }));
};
getStageList();
</script>

<style scoped lang="scss">
::v-deep(.arco-table) {
  margin: 20px 0;
}

::v-deep(.arco-pagination) {
  justify-content: flex-end;
}

.model-content {
  ::v-deep(.arco-form) {
    margin-top: 24px;
  }
}

.modal-message {
  text-align: center;

  .del-name {
    width: 80%;
    margin: 12px auto;
    height: 60px;
    line-height: 60px;
    border: 1px solid #dcdfe6;
  }
}

::v-deep(thead .arco-table-th) {
  background: #F2F6FC;
}

::v-deep(tbody) {
  .arco-table-tr:nth-child(even) {
    .arco-table-td {
      background-color: #F2F6FC !important;
    }
  }
}
</style>
